package com.xjrsoft.module.upload.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.common.utils.UploadUtil;
import com.xjrsoft.core.tool.utils.DateUtil;
import com.xjrsoft.core.tool.utils.IoUtil;
import com.xjrsoft.core.tool.utils.StringPool;
import com.xjrsoft.module.base.entity.XjrBaseAnnexesFile;
import com.xjrsoft.module.base.service.IXjrBaseAnnexesFileService;
import com.xjrsoft.module.upload.vo.UploadFileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Paths;
import java.util.Date;

/**
 * <p>
 * 任务调度模板基础信息表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-12-23
 */
@RestController
@RequestMapping("/upload")
//@AllArgsConstructor
@Api(value = "/upload", tags = "文件上传模块")
public class UploadController {

    @Autowired
    private  IXjrBaseAnnexesFileService annexesFileService;



    @Value("${xjrsoft.global-config.oss.enabled}")
    private  boolean enabled;

    @PostMapping
    @ApiOperation(value = "单文件上传")
    public Response<UploadFileVo> uploadFile(@RequestParam(value = "name", required = false) String fileName, @RequestParam(value = "file") MultipartFile multipartFile) throws Exception {
        String folderId = IdWorker.get32UUID();
        String fileId = IdWorker.get32UUID();
        XjrBaseAnnexesFile xjrBaseAnnexesFile = uploadFile(multipartFile, folderId, fileId, fileName);
        if (xjrBaseAnnexesFile!=null) {
            UploadFileVo uploadFileVo = new UploadFileVo();
            uploadFileVo.setFolderId(folderId);
            uploadFileVo.getFileIdList().add(fileId);
//            uploadFileVo.getFileUrlList().add(xjrBaseAnnexesFile.getFilePath());
//            String monthFormat = DateUtil.format(new Date(), "yyyyMM");
//            String filename = multipartFile.getOriginalFilename();
//            String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
            // 保存文件到文件夹
//            String fileDirPath = StringPool.SLASH + "uploadFiles" + StringPool.SLASH + monthFormat + StringPool.SLASH + fileId + StringPool.DOT + suffix;
            String getFileApiUrlPrefix = "/annexes-files/";
            uploadFileVo.getFileAddrList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
            uploadFileVo.getFileUrlList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
            uploadFileVo.getAddressList().add(xjrBaseAnnexesFile.getFilePath());
            return Response.ok(uploadFileVo);
        }else {
            return Response.notOk();
        }
    }

    @PostMapping("/{folderId}")
    @ApiOperation(value = "单文件上传")
    public Response<UploadFileVo> uploadFileToFolder(@PathVariable String folderId, @RequestParam(value = "name", required = false) String fileName, @RequestParam(value = "file", required = true) MultipartFile multipartFile) throws Exception {
        String fileId = IdWorker.get32UUID();
        XjrBaseAnnexesFile xjrBaseAnnexesFile = uploadFile(multipartFile, folderId, fileId, fileName);
        if (xjrBaseAnnexesFile!=null) {
            UploadFileVo uploadFileVo = new UploadFileVo();
            uploadFileVo.setFolderId(folderId);
            uploadFileVo.getFileIdList().add(fileId);
//            uploadFileVo.getFileUrlList().add(xjrBaseAnnexesFile.getFilePath());
//            String monthFormat = DateUtil.format(new Date(), "yyyyMM");
//            String filename = multipartFile.getOriginalFilename();
//            String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
//
//            // 保存文件到文件夹
//            String fileDirPath = StringPool.SLASH + "uploadFiles" + StringPool.SLASH + monthFormat + StringPool.SLASH + fileId + StringPool.DOT + suffix;
            String getFileApiUrlPrefix = "/annexes-files/";
            uploadFileVo.getFileAddrList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
            uploadFileVo.getFileUrlList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
            uploadFileVo.getAddressList().add(xjrBaseAnnexesFile.getFilePath());
//            uploadFileVo.getFileAddrList().add(fileDirPath);
            return Response.ok(uploadFileVo);
        }
        return Response.notOk();
    }

    @PostMapping("/multiple-file-upload")
    @ApiOperation(value = "多文件上传")
    public Response<UploadFileVo> uploadFiles(@RequestParam(value = "file") MultipartFile[] multipartFiles) throws Exception {
        UploadFileVo uploadFileVo = new UploadFileVo();
        if (multipartFiles != null && multipartFiles.length > 0) {
            String folderId = IdWorker.get32UUID();
            uploadFileVo.setFolderId(folderId);
            for (MultipartFile multipartFile : multipartFiles) {
                String fileId = IdWorker.get32UUID();
                XjrBaseAnnexesFile xjrBaseAnnexesFile = uploadFile(multipartFile, folderId, fileId);
                if (xjrBaseAnnexesFile!=null) {
                    uploadFileVo.getFileIdList().add(fileId);
//                    uploadFileVo.getFileUrlList().add(xjrBaseAnnexesFile.getFilePath());

//                    String monthFormat = DateUtil.format(new Date(), "yyyyMM");
//                    String filename = multipartFile.getOriginalFilename();
//                    String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);

                    // 保存文件到文件夹
//                    String fileDirPath = StringPool.SLASH + "uploadFiles" + StringPool.SLASH + monthFormat + StringPool.SLASH + fileId + StringPool.DOT + suffix;
//                    uploadFileVo.getFileAddrList().add(fileDirPath);
                    String getFileApiUrlPrefix = "/annexes-files/";
                    uploadFileVo.getFileAddrList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
                    uploadFileVo.getFileUrlList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
                    uploadFileVo.getAddressList().add(xjrBaseAnnexesFile.getFilePath());
                }
            }

        }
        return Response.ok(uploadFileVo);
    }

    @PostMapping("/multiple-file-upload/{folderId}")
    @ApiOperation(value = "多文件上传")
    public Response<UploadFileVo> uploadFilesToFolder(@PathVariable String folderId, @RequestParam(value = "file") MultipartFile[] multipartFiles) throws Exception {
        UploadFileVo uploadFileVo = new UploadFileVo();
        if (multipartFiles != null && multipartFiles.length > 0) {
            uploadFileVo.setFolderId(folderId);
            for (MultipartFile multipartFile : multipartFiles) {
                String fileId = IdWorker.get32UUID();
                XjrBaseAnnexesFile xjrBaseAnnexesFile = uploadFile(multipartFile, folderId, fileId);
                if (xjrBaseAnnexesFile!=null) {
                    uploadFileVo.getFileIdList().add(fileId);
//                    uploadFileVo.getFileUrlList().add(xjrBaseAnnexesFile.getFilePath());
//                    String monthFormat = DateUtil.format(new Date(), "yyyyMM");
//                    String filename = multipartFile.getOriginalFilename();
//                    String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
//
//                    // 保存文件到文件夹
//                    String fileDirPath = StringPool.SLASH + "uploadFiles" + StringPool.SLASH + monthFormat + StringPool.SLASH + fileId + StringPool.DOT + suffix;
//                    uploadFileVo.getFileAddrList().add(fileDirPath);
                    String getFileApiUrlPrefix = "/annexes-files/";
                    uploadFileVo.getFileAddrList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
                    uploadFileVo.getFileUrlList().add(getFileApiUrlPrefix + xjrBaseAnnexesFile.getId());
                    uploadFileVo.getAddressList().add(xjrBaseAnnexesFile.getFilePath());
                }
            }
        }
        return Response.ok(uploadFileVo);
    }

    private XjrBaseAnnexesFile uploadFile(MultipartFile multipartFile, String folderId, String fileId) throws Exception {
        return uploadFile(multipartFile, folderId, fileId, null);
    }

    private XjrBaseAnnexesFile uploadFile(MultipartFile multipartFile, String folderId, String fileId, String fieldName) throws Exception {
        String filePath ="";
        String name = StringUtils.isEmpty(fieldName) ? multipartFile.getOriginalFilename() : fieldName;
        String suffix = StringUtils.substringAfterLast(name, StringPool.DOT);
        if(enabled){
            //保存到云服务器
            filePath= UploadUtil.uploadFile(multipartFile);
        }else {
            //保存到本地
            String monthFormat = DateUtil.format(new Date(), "yyyyMM");
            // 保存文件到文件夹
            String fileDirPath = StringPool.SLASH + "static" + StringPool.SLASH + "uploadFiles" + StringPool.SLASH + monthFormat;
            File fileDir = new File(IoUtil.getProjectPath() + fileDirPath);
            if (!fileDir.exists()){
                fileDir.mkdirs();
            }
            filePath = fileDirPath + StringPool.SLASH + fileId + StringPool.DOT + suffix;
            String savePath = fileDir + StringPool.SLASH + fileId + StringPool.DOT + suffix;
            multipartFile.transferTo(Paths.get(savePath));
        }

        XjrBaseAnnexesFile annexesFile = new XjrBaseAnnexesFile();
        annexesFile.setId(fileId);
        annexesFile.setFolderId(folderId);
        annexesFile.setFileName(name);
        annexesFile.setFilePath(filePath);
        annexesFile.setFileSize(String.valueOf(multipartFile.getSize()));
        annexesFile.setFileExtensions(StringPool.DOT + suffix);
        annexesFile.setFileType(suffix);
        annexesFileService.save(annexesFile);
        return annexesFile;
    }
}
